<?php
/**
 * Created by PhpStorm.
 * User: Guojunchen
 * Date: 2018/4/17
 * Time: 17:54
 */

namespace app\common\lib;

/**
 * 图片上传
 * Class Upload
 * @package app\common\lib
 */
class Upload {

    protected static $allow_file_type = ['jpg', 'gif', 'bmp', 'jpeg', 'png'];// 允许上传文件的类型

    /**
     * 文件上传方法
     * @param $file_name 根据客户端所提交的内容，如：realname 实名认证
     * @param string $bucket 存储域
     * @return mixed
     */
    public static function uploadByFile($file_name, $bucket = ''){
        if (!$_FILES[$file_name]){
            renderJson('文件不存在', 0);
        }
        $tmp_file_name = $_FILES[$file_name]['name'];
        $file_path = $_FILES[$file_name]['tmp_name'];
        $file_size = $_FILES[$file_name]['size'];

        if (!$file_path || !file_exists($file_path)){
            renderJson('文件路径不合法', 0);
        }
        $date_now = date('Y-m-d H:i:s');
        $tmp_file_extend = explode('.', $tmp_file_name);
        $file_type = strtolower(end($tmp_file_extend));// 文件后缀名

        // 验证文件类型
        if (!in_array($file_type, self::$allow_file_type)){
            renderJson('上传文件类型不支持', 0);
        }
        // 验证文件大小
        if($file_size > config('app.upload_max_size')){
            renderJson('上传文件大小超过限制', 0);
        }
        $upload_config = config('app.upload');
        if (!isset($upload_config[$bucket])){
            renderJson('指定的bucket不存在或者没有配置');
        }

        $hash_key = md5(file_get_contents($file_path));
        $upload_dir_path = ROOT_PATH.'/public';
        $folder_name = $upload_config[$bucket].'/'.date('Ymd', strtotime($date_now));
        $upload_dir = $upload_dir_path.$folder_name;

        if (!file_exists($upload_dir)){
            mkdir($upload_dir, 0777, true);
            chmod($upload_dir, 0777);
        }

        $upload_file_name = "{$folder_name}/{$hash_key}.".$file_type;

        if (is_uploaded_file($file_path)){
            if (!move_uploaded_file($file_path, $upload_dir_path.$upload_file_name)){
                renderJson('上传失败，系统繁忙请稍后再试');
            }
        } else{
            file_put_contents($upload_dir_path.$upload_file_name, file_get_contents($file_path));
        }

        $data = array(
            'file_name' => $tmp_file_name,
            'save_name' => $upload_file_name,
            'file_ext' => $file_type,
            'file_size' => $file_size,
            'bucket' => $bucket,
            'on_time' => time(),
            'file_status' => 0
        );

        try {
            model('File')->add($data);
        }catch (\Exception $e){
            renderJson('提交失败', 0);
        }

        return $upload_file_name;
    }
}